package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import model.Collection;

public class ScoredEntities extends HashMap<String, Double> {

	/**
	 * Creates an empty map and nothing else
	 */
	public ScoredEntities() {

	}

	/**
	 * Read the entities and their scores from a file
	 * 
	 * @param file
	 */
	public ScoredEntities(File file) {
		// line format: abortifacient#n -0.125
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = reader.readLine()) != null) {
				int sharpLoc = line.indexOf("#");
				int tabLoc = line.indexOf('\t');
				addWord(line.substring(0, sharpLoc),
						Double.parseDouble(line.substring(tabLoc + 1,
								line.length())));
				// System.out.println(line.substring(sharpLoc + 1,
				// tabLoc));//The POS tag. Ignored for now.
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public boolean hasWord(String word) {
		return containsKey(word);
	}

	public void addWord(String word, double score) {
		put(word, score);
	}

	public void updateWord(String word, int scoreDiff) {
		put(word, get(word) + scoreDiff);
	}

	public double getScore(String entity) {
		return containsKey(entity) ? get(entity) : 0;
	}

	public void printTopN(int N) {
		List<String> sorted = Collection.sortByValueDesc(this);
		int count = 0;
		for (String concept : sorted) {
			System.out.println(concept + " : " + get(concept));
			if (++count >= N) {
				break;
			}
		}
	}

	public List<String> sortByLength() {
		HashMap<String, Integer> m = new HashMap<String, Integer>();
		for (String entity : this.keySet()) {
			m.put(entity, entity.length());
		}
		return Collection.sortByValueDesc(m);
	}
}
